package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class ArrayListAndLinkedListCompare {
	public static void main(String[] args) {
//		testAddToEnd(10000000);
//		testAddToIndex(10000000);
		
		List<String> list = init(50000);
		System.out.println("ArrayList消耗时间："+testGet(new ArrayList<String>(list)));
		System.out.println("LinkedList消耗时间："+testGet(new LinkedList<String>(list)));
	}

	/**
	 * 前提:需要设置jvm参数-Xms1024M -Xmx1024M(保证内存足够大，防止jvm内存回收)
	 * 结论:当大于1000万数据量时，具有初始容量的 ArrayList明显比LinkedList快很多
	 */
	private static void testAddToEnd(int count) {
		long startTime1 = System.currentTimeMillis();
		List<String> arrayList1 = new ArrayList<String>(1000000);
		for (int i = 0; i < count; i++) {
			arrayList1.add("a" + i);
		}
		long endTime1 = System.currentTimeMillis();
		System.out.println("有初始容量的arrayList数量:" + arrayList1.size() + "---耗时:" + (endTime1 - startTime1));
		
		long startTime2 = System.currentTimeMillis();
		List<String> arrayList2 = new ArrayList<String>();
		for (int i = 0; i < count; i++) {
			arrayList2.add("b" + i);
		}
		long endTime2 = System.currentTimeMillis();
		System.out.println("arrayList数量:" + arrayList2.size() + "---耗时:" + (endTime2 - startTime2));
		
		long startTime3 = System.currentTimeMillis();
		List<String> linkedList = new LinkedList<String>();
		for (int i = 0; i < count; i++) {
			linkedList.add("b" + i);
		}
		long endTime3 = System.currentTimeMillis();
		System.out.println("linkedList数量:" + linkedList.size() + "---耗时:" + (endTime3 - startTime3));
	}
	
	/**
	 * 结论:在ArrayList的中间插入或删除一个元素意味着这个列表中剩余的元素都会被移动；而在LinkedList的中间插入或删除一个元素的开销是固定的
	 */
	private static void testAddToIndex(int count) {
		long startTime1 = System.currentTimeMillis();
		List<String> arrayList1 = new ArrayList<String>(count);
		for (int i = 0; i < count; i++) {
			arrayList1.add(0,"a" + i);
		}
		long endTime1 = System.currentTimeMillis();
		System.out.println("有初始容量的arrayList数量:" + arrayList1.size() + "---耗时:" + (endTime1 - startTime1));
				
		long startTime3 = System.currentTimeMillis();
		List<String> linkedList = new LinkedList<String>();
		for (int i = 0; i < count; i++) {
			linkedList.add(0,"b" + i);
		}
		long endTime3 = System.currentTimeMillis();
		System.out.println("linkedList数量:" + linkedList.size() + "---耗时:" + (endTime3 - startTime3));
	}
	
	private static List<String> init(int count) {
		String[] strArr = new String[count];
		for (int i = 0; i < count; i++) {
			strArr[i] = "a" + i;			
		}
		return Arrays.asList(strArr);
	}
	//随机访问
	private static long testGet(List<String> list) {
		long startTime = System.currentTimeMillis();
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
		long endTime = System.currentTimeMillis();
		return endTime - startTime;
	}
}
